#include "key.h"

#define MODE_INPUT                        0
#define MODE_OUTPUT_SPEED_10MHZ           1
#define MODE_OUTPUT_SPEED_2MHZ            2
#define MODE_OUTPUT_SPEED_50MHZ           3

#define CONF_OUTPUT_GENERAL_PUSH_PULL     0
#define CONF_OUTPUT_GENERAL_OPEN_DRAIN    1
#define CONF_OUTPUT_ALTERNATE_PUSH_PULL   2
#define CONF_OUTPUT_ALTERNATE_OPEN_DRAIN  3

#define CONF_INPUT_ANALOG                 0
#define CONF_INPUT_FLOATING               1
#define CONF_INPUT_PULL_UP_DOWN           2
#define CONF_INPUT_RESERVED               3

void Key_Init()
{
    // 1. 配置时钟: RCC_APB2ENR 寄存器
    RCC->APB2ENR |= RCC_APB2ENR_IOPFEN;
    RCC->APB2ENR |= RCC_APB2ENR_AFIOEN;

    // 2. GPIO工作模式配置: GPIOF_CRH 寄存器
    GPIOF->CRH &= ~(0xF << (2 * 4));
    GPIOF->CRH |= MODE_INPUT              << (2 * 4);
    GPIOF->CRH |= CONF_INPUT_PULL_UP_DOWN << (2 * 4 + 2);

    GPIOF->ODR &= ~GPIO_ODR_ODR10;      // 输入下拉

    // 3. AFIO配置引脚复用选择
    AFIO->EXTICR[2] |= AFIO_EXTICR3_EXTI10_PF;

    // 4. 配置EXTI: 上升沿触发寄存器, 中断屏蔽寄存器
    EXTI->RTSR |= EXTI_RTSR_TR10;
    EXTI->IMR  |= EXTI_IMR_MR10;

    // 5. NVIC配置
    NVIC_SetPriorityGrouping(3);    // 全部都是抢占优先级
    NVIC_SetPriority(EXTI15_10_IRQn, 3);
    NVIC_EnableIRQ(EXTI15_10_IRQn);
}

// 中断服务程序
void EXTI15_10_IRQHandler(void)
{
    // 先清除中断挂起标志位
    EXTI->PR |= EXTI_PR_PR10;

    // 防抖延迟
    Delay_ms(10);

    // 判断如果依然保持高电平，就翻转LED1
    if(GPIOF->IDR & GPIO_IDR_IDR10)
    {
        LED_Toggle(LED1);
    }
}
